//
//  EVTextField.m
//  EVClub
//
//  Created by Eric on 15/3/30.
//  Copyright (c) 2015年 BitRice. All rights reserved.
//
#import "UIView+EV.h"
#import "UIColor+EV.h"
#import "EVTextField.h"

@interface EVTextField()

@property(nonatomic,strong) UIImageView *downImageView;
@property(nonatomic,strong) UILabel *lineLabel;
@property(nonatomic,strong) UIButton *clickBtn;
@property(nonatomic,strong) EVTextFieldDefaultDelegate *defaultDelegate;
@end
@implementation EVTextField

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        [self initialize];
        self.textColor = [UIColor ev_majorTextColor];
        self.font = [UIFont systemFontOfSize:15];
    }
    return self;
}
-(void)initialize
{
    self.numberOfLimitChar = UINTPTR_MAX ;
    self.paddingLeft = self.paddingRight = 5;
    CoverManager *acm = [[CoverManager alloc] initWithUIView:self];
    self.coverManager = acm;
    self.defaultDelegate = [[EVTextFieldDefaultDelegate alloc]init];
    _defaultDelegate.targetField = self;
    self.delegate = _defaultDelegate;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self initialize];
    }
    return self;
}
-(void)setSelectMode:(BOOL)selectMode
{
    _selectMode = selectMode;
    if(_selectMode)
    {
        if(!_downImageView) self.downImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"down.png"]];
        if(!_lineLabel)
        {
            self.lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.ev_width - self.ev_height, 0, 1, self.ev_height)];
            _lineLabel.backgroundColor = [UIColor colorWithCGColor:self.layer.borderColor];
        }
        [_downImageView setCenter:CGPointMake(_lineLabel.ev_right + self.ev_height/2, self.ev_height/2)];
        if(!_clickBtn)
        {
            self.clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_clickBtn setFrame:self.bounds];
            [_clickBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
        }
        [self addSubview:_downImageView];
        [self addSubview:_lineLabel];
        [self addSubview:_clickBtn];
        self.paddingRight = 10 + self.ev_height;
    }
    else
    {
        [_clickBtn removeFromSuperview];
        [_downImageView removeFromSuperview];
        [_lineLabel removeFromSuperview];
        self.paddingLeft = self.paddingRight = 10;
    }
}
-(UIView*)inputAccessoryView
{
    if(!_showInputAccessoryView) return nil;
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 36)];
    toolBar.barStyle = UIBarStyleDefault;
    toolBar.backgroundColor = RGB(247, 247, 247);
    toolBar.tintColor = RGB(247, 247, 247);
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    item.width = [[UIScreen mainScreen] bounds].size.width - 100;
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(finish)];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)];
    NSArray *array = [NSArray arrayWithObjects:item1,item,item2, nil];
    toolBar.items = array;
    return toolBar;
}
-(BOOL)becomeFirstResponder
{
    [_coverManager refresh];
    return [super becomeFirstResponder];
}
-(void)finish
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    if([_clickDelegate respondsToSelector:@selector(FinishButtonDidPressed:)])
    {
        [_clickDelegate FinishButtonDidPressed:self];
    }
}
-(void)cancel
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    if([_clickDelegate respondsToSelector:@selector(CancelButtonDidPressed:)])
    {
        [_clickDelegate CancelButtonDidPressed:self];
    }
}
-(void)click
{
    if([_clickDelegate respondsToSelector:@selector(EVTextFieldDidPressed:)])
    {
        [_clickDelegate EVTextFieldDidPressed:self];
    }
}
-(void)setCoverManagerView:(UIView *)coverManagerView
{
    [self performSelector:@selector(delaySetManagerView:) withObject:coverManagerView afterDelay:0.01f];
}
-(void)delaySetManagerView:(UIView*)coverManagerView
{
    self.coverManager.theSuperView = coverManagerView;
    self.coverManager.recoverRect = _recoverRect;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectMake(bounds.origin.x + self.paddingLeft,
                      bounds.origin.y +self.paddingUp,
                      bounds.size.width - 2*self.paddingRight, bounds.size.height-2*self.paddingDown);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}
-(void)dealloc
{
    [self.coverManager clean];
}
@end
@interface EVTextFieldDefaultDelegate(){
    NSString *currentText;
}
@end
@implementation EVTextFieldDefaultDelegate
-(id)init
{
    self = [super init];
    if(self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidEndTextChanged:) name:UITextFieldTextDidChangeNotification object:nil];
    }
    return self;
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - UITextFieldDelegate
#pragma mark -
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldTextDidEndTextChanged:(NSNotification *)notification {
    if(notification.object == _targetField)
    {
    NSUInteger maxTextLength = _targetField.numberOfLimitChar;
    BOOL currentTextFull = maxTextLength != 0 && currentText.length >= maxTextLength;
    if (_targetField.markedTextRange == nil) {
        currentText = _targetField.text;
        if (_targetField.text.length > maxTextLength) {
            _targetField.text = [_targetField.text substringToIndex:maxTextLength];
        }
        //NSInteger remainTextCount = maxTextLength - _targetField.text.length;
        
    } else if (currentTextFull) {
        [_targetField unmarkText];
    }
        if([_targetField.clickDelegate respondsToSelector:@selector(EVTextFieldTextDidChanged:)])
        {
            [_targetField.clickDelegate EVTextFieldTextDidChanged:_targetField];
        }
    }
}
@end
